package com.imyuanma.qingyun.ums.controller;

import com.imyuanma.qingyun.common.config.security.DefaultPasswordEncoder;
import com.imyuanma.qingyun.common.model.request.WebRequest;
import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.AssertUtil;
import com.imyuanma.qingyun.common.util.StringUtil;
import com.imyuanma.qingyun.ums.model.UmsUser;
import com.imyuanma.qingyun.ums.model.enums.EUmsUserStatusEnum;
import com.imyuanma.qingyun.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * sso
 *
 * @author wangjy
 * @date 2022/07/26 23:16:11
 */
@RestController
@RequestMapping(value = "/sso")
public class UmsSsoController {


    @Autowired
    private IUmsUserService umsUserService;

    /**
     * 注册
     * @param webRequest
     * @return
     */
    @PostMapping("/register")
    public Result<List<UmsUser>> register(@RequestBody WebRequest<UmsUser> webRequest) {
        UmsUser user = webRequest.getBody();
        AssertUtil.notNull(user);
        AssertUtil.notBlank(user.getAccount());
        AssertUtil.notBlank(user.getPassword());
        // 加密器
        DefaultPasswordEncoder passwordEncoder = DefaultPasswordEncoder.newInstance("qingyun");
        // 解析用户输入的密码
        String pwd = passwordEncoder.parseInputPassword(user.getPassword());
        // 密码编码后入库
        user.setPassword(passwordEncoder.encode(pwd));
        // 有效状态
        user.setStatus(EUmsUserStatusEnum.ENABLE.getCode());
        if (StringUtil.isBlank(user.getName())) {
            user.setName(user.getAccount());
        }
        if (user.getCompanyId() == null) {
            user.setCompanyId(1L);
        }
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setCreateUserId(1L);
        user.setUpdateUserId(1L);
        // 入库
        umsUserService.insertSelective(user);
        return Result.success();
    }
}
